package net.mingsoft.statistic.biz.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.mingsoft.basic.util.SqlUtil;
import net.mingsoft.statistic.action.q.DataMapQuery;
import net.mingsoft.statistic.action.q.DataQuery;
import net.mingsoft.statistic.action.r.DataMapResponse;
import net.mingsoft.statistic.action.r.DataTable;
import net.mingsoft.statistic.action.r.TableHeader;
import net.mingsoft.statistic.biz.DataMapBiz;
import net.mingsoft.statistic.dao.ZKTableDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gengfa
 * @date 22/02/17
 */
@Service
public class DataMapBizImpl implements DataMapBiz {

    @Resource
    ZKTableDao tableDao;

    @Override
    public Page<DataTable> tables(DataMapQuery query) {
        if (StringUtils.isNotBlank(query.getTableName())) {
            query.setTableName(SqlUtil.likeStr(query.getTableName()));
        }
        return tableDao.selectAllTables(new Page<>(query.getPageNo(), query.getPageSize()), query.getTableName());
    }

    @Override
    public DataMapResponse data(DataQuery query) {
        DataMapResponse response = new DataMapResponse();
        List<TableHeader> tableHeaders = new ArrayList<>();
        if (query.getId() == null || query.getId() <= 0) {
            tableHeaders = tableDao.selectTableFieldsByTableName(query.getTableName());
        } else {
            tableHeaders = tableDao.selectTableFieldsById(query.getId());
        }
        Page<Map<String, Object>> page = tableDao.selectPageByTableName(
                new Page<>(query.getPageNo(), query.getPageSize()),
                query.getTableName());
        page.getRecords().forEach(o -> {
            Object createdDate = o.get("created_date");
            if (createdDate instanceof LocalDateTime) {
                String createdDateStr = ((LocalDateTime) o.get("created_date")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                o.put("created_date", createdDateStr);
            }
        });
        response.setHeaders(tableHeaders).setPage(page);
        return response;
    }
}
